﻿namespace MicroCloud.Identity
{
    #region "组织机构存储基类"
    /// <summary>
    /// 组织机构存储基类
    /// </summary>
    /// <typeparam name="TOrganization">组织机构实体类型</typeparam>
    /// <typeparam name="TOrganizationKey">组织机构编号类型</typeparam>
    /// <typeparam name="TOrganizationClaim">组织机构声明类型</typeparam>
    /// <typeparam name="TOrganizationClaimKey">组织机构声明编号类型</typeparam>
    /// <typeparam name="TRoleOrganization">角色组织机构实体类型</typeparam>
    /// <typeparam name="TRoleOrganizationKey">角色组织机构编号类型</typeparam>
    /// <typeparam name="TRoleKey">角色编号类型</typeparam>
    /// <typeparam name="TUserOrganization">用户组织机构实体类型</typeparam>
    /// <typeparam name="TUserOrganizationKey">用户组织机构编号类型</typeparam>
    /// <typeparam name="TUserKey">用户编号类型</typeparam>
    public abstract class OrganizationStoreBase<TOrganization, TOrganizationKey, TOrganizationClaim, TOrganizationClaimKey, TRoleOrganization, TRoleOrganizationKey, TRoleKey, TUserOrganization, TUserOrganizationKey, TUserKey>
        : Disposable, IQueryableOrganizationStore<TOrganization>, IOrganizationClaimStore<TOrganization>
        where TOrganization : OrganizationBase<TOrganizationKey, TUserKey>
        where TOrganizationKey : struct, IEquatable<TOrganizationKey>
        where TOrganizationClaim : OrganizationClaimBase<TOrganizationClaimKey, TOrganizationKey>, new()
        where TOrganizationClaimKey : struct, IEquatable<TOrganizationClaimKey>
        where TRoleOrganization : RoleOrganizationBase<TRoleOrganizationKey, TRoleKey, TOrganizationKey>, new()
        where TRoleOrganizationKey : struct, IEquatable<TRoleOrganizationKey>
        where TRoleKey : struct, IEquatable<TRoleKey>
        where TUserOrganization : UserOrganizationBase<TUserOrganizationKey, TUserKey, TOrganizationKey>, new()
        where TUserOrganizationKey : struct, IEquatable<TUserOrganizationKey>
        where TUserKey : struct, IEquatable<TUserKey>
    {
        //字段
        private readonly IServiceProvider _provider;

        #region "属性"
        #region "获取 事件总线"
        /// <summary>
        /// 获取 事件总线
        /// </summary>
        protected IEventBus EventBus => _provider.GetService<IEventBus>();
        #endregion
        #region "获取 组织机构仓储"
        /// <summary>
        /// 获取 组织机构仓储
        /// </summary>
        protected IRepository<TOrganization, TOrganizationKey> OrganizationRepository => _provider.GetService<IRepository<TOrganization, TOrganizationKey>>();
        #endregion
        #region "获取 组织机构声明仓储"
        /// <summary>
        /// 获取 组织机构声明仓储
        /// </summary>
        protected IRepository<TOrganizationClaim, TOrganizationClaimKey> OrganizationClaimRepository => _provider.GetService<IRepository<TOrganizationClaim, TOrganizationClaimKey>>();
        #endregion

        #region "获取 角色组织机构映射仓储"
        /// <summary>
        /// 获取 角色组织机构映射仓储
        /// </summary>
        protected IRepository<TRoleOrganization, TRoleOrganizationKey> RoleOrganizationRepository => _provider.GetService<IRepository<TRoleOrganization, TRoleOrganizationKey>>();
        #endregion
        #region "获取 用户组织机构映射仓储"
        /// <summary>
        /// 获取 用户组织机构映射仓储
        /// </summary>
        protected IRepository<TUserOrganization, TUserOrganizationKey> UserOrganizationRepository => _provider.GetService<IRepository<TUserOrganization, TUserOrganizationKey>>();
        #endregion

        #endregion

        #region "属性 - Implementation of IQueryableOrganizationStore<TOrganization>"
        #region "获取 组织机构查询数据集"
        /// <summary>
        /// 获取 组织机构查询数据集
        /// </summary>
        public IQueryable<TOrganization> Organizations => OrganizationRepository.QueryAsNoTracking();
        #endregion

        #endregion

        #region "属性 - Implementation of IOrganizationClaimStore<TOrganization>"
        #region "获取 组织机构声明查询数据集"
        /// <summary>
        /// 获取 组织机构声明查询数据集
        /// </summary>
        public IQueryable<TOrganizationClaim> OrganizationClaims => OrganizationClaimRepository.QueryAsNoTracking();
        #endregion

        #endregion

        #region "构造函数"
        #region "初始化一个组织机构存储基类的新实例"
        /// <summary>
        /// 初始化一个组织机构存储基类 <see cref="OrganizationStoreBase{TOrganization, TOrganizationKey, TOrganizationClaim, TOrganizationClaimKey, TRoleOrganization, TRoleOrganizationKey, TRoleKey, TUserOrganization, TUserOrganizationKey, TUserKey}"/> 的新实例
        /// </summary>
        /// <param name="provider">服务提供程序</param>
        protected OrganizationStoreBase(IServiceProvider provider)
        {
            _provider = provider;
        }
        #endregion

        #endregion

        #region "方法"
        #region "将提供的<paramref name="id"/>转换为强类型键对象"
        /// <summary>
        /// 将提供的<paramref name="id"/>转换为强类型键对象
        /// </summary>
        /// <param name="id">要转换的id</param>
        /// <returns><typeparamref name="TOrganizationKey"/>的实例表示提供的<paramref name="id"/></returns>
        public virtual TOrganizationKey ConvertIdFromString(string id)
        {
            if (id == null)
            {
                return default;
            }

            return (TOrganizationKey)TypeDescriptor.GetConverter(typeof(TOrganizationKey)).ConvertFromInvariantString(id);
        }
        #endregion
        #region "将提供的<paramref name="id"/>转换为其字符串表示形式"
        /// <summary>
        /// 将提供的<paramref name="id"/>转换为其字符串表示形式
        /// </summary>
        /// <param name="id">要转换的id</param>
        /// <returns>提供<paramref name="id"/>的<see cref="string"/>的表示</returns>
        public virtual string ConvertIdToString(TOrganizationKey id)
        {
            if (id.Equals(default))
            {
                return null;
            }

            return id.ToString();
        }
        #endregion

        #region "如果已释放，则抛出异常"
        /// <summary>
        /// 如果已释放，则抛出异常
        /// </summary>
        protected void ThrowIfDisposed()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
        }
        #endregion

        #endregion

        #region "方法 - Implementation of IOrganizationStore<TOrganization>"
        #region "检查组织机构信息是否存在"
        /// <summary>
        /// 检查组织机构信息是否存在
        /// </summary>
        /// <param name="predicate">检查谓语表达式</param>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>组织机构是否存在</returns>
        public virtual bool CheckOrganizationExists(Expression<Func<TOrganization, bool>> predicate, string organizationId = default)
        {
            return OrganizationRepository.CheckExists(predicate, ConvertIdFromString(organizationId));
        }
        #endregion
        #region "在存储中创建一个新组织机构"
        /// <summary>
        /// 在存储中创建一个新组织机构
        /// </summary>
        /// <param name="organization">要在存储中创建的组织机构</param>
        /// <returns>表示一个 <see cref="OperationResult" /> </returns>
        public virtual OperationResult Create(TOrganization organization)
        {
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNullOrEmpty(organization.Code, nameof(organization.Code));

            organization.IsSystem = false;
            if (organization.IsDefault)
            {
                var defaultOrganization = OrganizationRepository.QueryAsNoTracking(m => m.IsDefault, false).FirstOrDefault();
                if (defaultOrganization != null)
                {
                    defaultOrganization.IsDefault = !organization.IsDefault;
                    var result2 = OrganizationRepository.Update(defaultOrganization);
                    if (!result2.Succeeded)
                    {
                        return result2;
                    }
                }
            }
            if (organization.EnableLogin)
            {
                if (organization.Type == OrganizationType.Department)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 不允许启用登录", organization.Name));
                }
            }
            if (organization.Type == OrganizationType.Corporation)
            {
                if (!organization.EnableLogin)
                {
                    return OperationResult.Error(I18N.T("[法人]组织机构 {0} 必须启用登录", organization.Name));
                }
            }
            organization.NormalizedName = NormalizeName(organization.Name);
            //父模块
            if (organization.ParentId == null || Equals(organization.ParentId, default(TOrganizationKey)))
            {
                if (organization.Type != OrganizationType.Virtual && organization.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("顶级组织机构类型必须为[虚拟]或[法人]"));
                }
            }
            string parentTreePathString = null;
            var parent = Organizations.Where(m => Equals(m.Id, organization.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
            if (parent != null)
            {
                parentTreePathString = parent.TreePathString;
            }
            if (parent == null && organization.ParentId != null && !Equals(organization.ParentId, default(TOrganizationKey)))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 的父级 {1} 不存在", organization.Name, organization.ParentId));
            }
            if (organization.EnableLogin && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Department)
                    {
                        return OperationResult.Error(I18N.T("启用登录的组织机构 {0} 存在一个类型为[部门]的父级 {1}", organization.Name, parentOrg.Name));
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
            }
            if (organization.Type == OrganizationType.Department && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Corporation)
                    {
                        break;
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
                if (parentOrg?.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 的父级 {1} 不为[法人]", organization.Name, parentOrg.Name));
                }
            }

            //重复性检查
            if (Organizations.Any(a => a.Code == organization.Code))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存", organization.Code));
            }
            var exist = Organizations.Where(m => Equals(m.ParentId, organization.ParentId) && Equals(m.Name, organization.Name) && !Equals(m.Id, organization.Id)).Select(n => n.Name).FirstOrDefault();
            if (exist != null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存在名称为 {1} 的子组织机构", exist, organization.Name));
            }

            //创建数据
            var result = OrganizationRepository.Insert(organization);
            if (result.Succeeded)
            {
                organization.TreePathString = organization.ParentId == null ? TreeHelper.FormatTreePathString(organization.Id) : TreeHelper.GetTreePathString(organization.Id, parentTreePathString);
                var result1 = OrganizationRepository.Update(organization);
                if (!result1.Succeeded)
                {
                    return result1;
                }

                //触发创建事件
                EntityEventData<TOrganization> eventData = new(OrganizationRepository.DbContext, OperateType.Insert) { Entities = new List<TOrganization> { organization } };
                EventBus?.Publish(eventData);

                return OperationResult.Success((object)organization);
            }
            return result;
        }
        #endregion
        #region "更新存储中的组织机构"
        /// <summary>
        /// 更新存储中的组织机构
        /// </summary>
        /// <param name="organization">要在存储中更新的组织机构</param>
        /// <returns>表示一个 <see cref="OperationResult" /></returns>
        public virtual OperationResult Update(TOrganization organization)
        {
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNullOrEmpty(organization.Code, nameof(organization.Code));

            var existOrganization = OrganizationRepository.QueryAsNoTracking(o => Equals(o.Id, organization.Id)).FirstOrDefault();
            if (existOrganization == null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不存在", organization.Id));
            }
            if (!Equals(existOrganization.IsSystem, organization.IsSystem))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不能修改 {1} 属性", organization.Id, nameof(organization.IsSystem)));
            }
            if (!Equals(existOrganization.Type, organization.Type))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不能修改 {1} 属性", organization.Id, nameof(organization.Type)));
            }
            if (organization.IsDefault)
            {
                var defaultOrganization = OrganizationRepository.QueryAsNoTracking(m => m.IsDefault && !Equals(m.Id, organization.Id), false).FirstOrDefault();
                if (defaultOrganization != null)
                {
                    defaultOrganization.IsDefault = !organization.IsDefault;
                    var result2 = OrganizationRepository.Update(defaultOrganization);
                    if (!result2.Succeeded)
                    {
                        return result2;
                    }
                }
            }
            if (organization.EnableLogin)
            {
                if (organization.Type == OrganizationType.Department)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 不允许启用登录", organization.Name));
                }
            }
            if (organization.Type == OrganizationType.Corporation)
            {
                if (!organization.EnableLogin)
                {
                    return OperationResult.Error(I18N.T("[法人]组织机构 {0} 必须启用登录", organization.Name));
                }
            }
            organization.NormalizedName = NormalizeName(organization.Name);
            //父模块
            if (organization.ParentId == null || Equals(organization.ParentId, default(TOrganizationKey)))
            {
                if (organization.Type != OrganizationType.Virtual && organization.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("顶级组织机构类型必须为[虚拟]或[法人]"));
                }
            }
            if (Equals(organization.Id, organization.ParentId))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 的父级不能指定为自己", organization.Name));
            }
            string parentTreePathString = null;
            var parent = Organizations.Where(m => Equals(m.Id, organization.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
            if (parent != null)
            {
                parentTreePathString = parent.TreePathString;
            }
            if (organization.EnableLogin && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Department)
                    {
                        return OperationResult.Error(I18N.T("启用登录的组织机构 {0} 存在一个类型为[部门]的父级 {1}", organization.Name, parentOrg.Name));
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
            }
            if (organization.Type == OrganizationType.Department && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Corporation)
                    {
                        break;
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
                if (parentOrg?.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 的父级 {1} 不为[法人]", organization.Name, parentOrg.Name));
                }
            }

            //重复性检查
            if (Organizations.Any(a => a.Code == organization.Code && !Equals(a.Id, organization.Id)))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存", organization.Code));
            }
            var exist = Organizations.Where(m => Equals(m.ParentId, organization.ParentId) && Equals(m.Name, organization.Name) && !Equals(m.Id, organization.Id)).Select(n => n.Name).FirstOrDefault();
            if (exist != null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存在名称为 {1} 的子组织机构", exist, organization.Name));
            }

            ////排序编号，不存在为1，否则同级最大+1
            //if (Equals(organization.OrderNo, default))
            //{
            //    var peerModules = Organizations.Where(m => m.ParentId.Equals(organization.ParentId)).Select(m => new { m.OrderNo }).ToArray();
            //    if (peerModules.Length == 0)
            //    {
            //        organization.OrderNo = 1;
            //    }
            //    else
            //    {
            //        decimal maxCode = peerModules.Max(m => m.OrderNo);
            //        organization.OrderNo = maxCode + 1;
            //    }
            //}

            organization.TreePathString = organization.ParentId == null ? TreeHelper.FormatTreePathString(organization.Id) : TreeHelper.GetTreePathString(organization.Id, parentTreePathString);

            //更新数据
            var result = OrganizationRepository.Update(organization);
            if (result.Succeeded)
            {
                //若父级变更且存在子级，同步更新子级
                if (!Equals(existOrganization.TreePathString, organization.TreePathString))
                {
                    var children = OrganizationRepository.QueryAsNoTracking(o => Equals(o.ParentId, organization.Id)).ToList();
                    if (children?.Count > 0)
                    {
                        foreach (var child in children)
                        {
                            var result2 = Update(child);
                            if (!result2.Succeeded)
                            {
                                return result2;
                            }
                        }
                    }
                }

                //触发更新事件
                EntityEventData<TOrganization> eventData = new(OrganizationRepository.DbContext, OperateType.Update) { Entities = new List<TOrganization> { organization } };
                EventBus?.Publish(eventData);

                return OperationResult.Success((object)organization);
            }
            return result;
        }
        #endregion
        #region "删除存储中的组织机构"
        /// <summary>
        /// 删除存储中的组织机构
        /// </summary>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>表示一个 <see cref="OperationResult" /></returns>
        public virtual OperationResult Delete(string organizationId)
        {
            ThrowIfDisposed();
            Check.NotNullOrEmpty(organizationId, nameof(organizationId));

            var organization = OrganizationRepository.Get(ConvertIdFromString(organizationId));
            if (organization == null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不存在", organizationId));
            }
            if (organization.IsSystem)
            {
                return OperationResult.Error(I18N.T("系统组织机构 {0} 不允许删除", organization.Name));
            }
            if (OrganizationRepository.CheckExists(m => m.ParentId.Equals(organization.Id)))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 存在子级", organization.Name));
            }
            //清除附属引用
            RoleOrganizationRepository.DeleteBatch(m => m.OrganizationId.Equals(organization.Id));
            UserOrganizationRepository.DeleteBatch(m => m.OrganizationId.Equals(organization.Id));

            var result = OrganizationRepository.Delete(organization);
            if (result.Succeeded)
            {
                //触发删除事件
                EntityEventData<TOrganization> eventData = new(OrganizationRepository.DbContext, OperateType.Delete) { Entities = new List<TOrganization> { organization } };
                EventBus?.Publish(eventData);

                return OperationResult.Success();
            }
            return result;
        }
        #endregion
        #region "删除存储中的组织机构"
        /// <summary>
        /// 删除存储中的组织机构
        /// </summary>
        /// <param name="organization">组织机构实体</param>
        /// <returns><see cref="Task" /> 表示一个异步的 <see cref="OperationResult" /></returns>
        public virtual OperationResult Delete(TOrganization organization)
        {
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));

            return Delete(ConvertIdToString(organization.Id));
        }
        #endregion
        #region "查找具有指定ID的组织机构"
        /// <summary>
        /// 查找具有指定ID的组织机构
        /// </summary>
        /// <param name="organizationId">要查找的组织机构编号</param>
        /// <returns>组织机构结果</returns>
        public TOrganization FindById(string organizationId)
        {
            ThrowIfDisposed();

            TOrganizationKey id = ConvertIdFromString(organizationId);
            return OrganizationRepository.Get(id);
        }
        #endregion
        #region "获取子级组织机构集合"
        /// <summary>
        /// 获取子级组织机构集合
        /// </summary>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>子级组织机构集合</returns>
        public virtual OrganizationDtoSimple[] GetChildOrganizations(string organizationId)
        {
            if (organizationId.IsMissing())
            {
                return Array.Empty<OrganizationDtoSimple>();
            }
            List<OrganizationDtoSimple> organizationDtoSimples = new();
            var organization = OrganizationRepository.Get(ConvertIdFromString(organizationId)) ?? throw new Exception(I18N.T("组织机构 {0} 不存在", organizationId));
            var childOrganizations = OrganizationRepository.QueryAsNoTracking(n => n.TreePathString.Contains(TreeHelper.FormatTreePathString(organizationId)) && !n.Id.Equals(ConvertIdFromString(organizationId))).ToList();
            if (childOrganizations != null)
            {
                foreach (var childOrganization in childOrganizations)
                {
                    organizationDtoSimples.Add(new OrganizationDtoSimple()
                    {
                        Id = ConvertIdToString(childOrganization.Id),
                        Type = childOrganization.Type,
                        Name = childOrganization.Name,
                        Description = childOrganization.Description,

                        OrderNo = childOrganization.OrderNo,
                        TreePathString = childOrganization.TreePathString,
                        ParentId = Equals(childOrganization.ParentId, default) ? null : ConvertIdToString(childOrganization.ParentId.Value),

                        EnableLogin = childOrganization.EnableLogin,
                        IsDefault = childOrganization.IsDefault,
                        IsSystem = childOrganization.IsSystem,

                        IsLocked = childOrganization.IsLocked,

                        CreatedTime = childOrganization.CreatedTime,
                    });
                }
            }
            return organizationDtoSimples.ToArray();
        }
        #endregion
        #region "获取父级组织机构集合"
        /// <summary>
        /// 获取父级组织机构集合
        /// </summary>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>父级组织机构集合</returns>
        public virtual OrganizationDtoSimple[] GetParentOrganizations(string organizationId)
        {
            if (organizationId.IsMissing())
            {
                return Array.Empty<OrganizationDtoSimple>();
            }
            List<OrganizationDtoSimple> organizationDtoSimples = new();
            var organization = OrganizationRepository.Get(ConvertIdFromString(organizationId)) ?? throw new Exception(I18N.T("组织机构 {0} 不存在", organizationId));
            if (!Equals(organization.ParentId, default(TOrganizationKey)))
            {
                var parent = Organizations.Where(m => m.Id.Equals(organization.ParentId)).FirstOrDefault();
                while (parent != null)
                {
                    organizationDtoSimples.Add(new OrganizationDtoSimple()
                    {
                        Id = ConvertIdToString(parent.Id),
                        Type = parent.Type,
                        Name = parent.Name,
                        Description = parent.Description,

                        OrderNo = parent.OrderNo,
                        TreePathString = parent.TreePathString,
                        ParentId = Equals(parent.ParentId, default) ? null : ConvertIdToString(parent.ParentId.Value),

                        EnableLogin = parent.EnableLogin,
                        IsDefault = parent.IsDefault,
                        IsSystem = parent.IsSystem,

                        IsLocked = parent.IsLocked,

                        CreatedTime = parent.CreatedTime,
                    });

                    parent = Organizations.Where(m => m.Id.Equals(parent.ParentId)).FirstOrDefault();
                }
            }
            return organizationDtoSimples.ToArray();
        }
        #endregion

        #region "异步检查组织机构信息是否存在"
        /// <summary>
        /// 异步检查组织机构信息是否存在
        /// </summary>
        /// <param name="predicate">检查谓语表达式</param>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>组织机构是否存在</returns>
        public virtual async Task<bool> CheckOrganizationExistsAsync(Expression<Func<TOrganization, bool>> predicate, string organizationId = default)
        {
            return await OrganizationRepository.CheckExistsAsync(predicate, ConvertIdFromString(organizationId));
        }
        #endregion
        #region "异步在存储中创建一个新组织机构"
        /// <summary>
        /// 异步在存储中创建一个新组织机构
        /// </summary>
        /// <param name="organization">要在存储中创建的组织机构</param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns><see cref="Task" /> 表示一个异步的 <see cref="OperationResult" /></returns>
        public virtual async Task<OperationResult> CreateAsync(TOrganization organization, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNullOrEmpty(organization.Code, nameof(organization.Code));

            organization.IsSystem = false;
            if (organization.IsDefault)
            {
                var defaultOrganization = OrganizationRepository.QueryAsNoTracking(m => m.IsDefault, false).FirstOrDefault();
                if (defaultOrganization != null)
                {
                    defaultOrganization.IsDefault = !organization.IsDefault;
                    var result2 = await OrganizationRepository.UpdateAsync(defaultOrganization);
                    if (!result2.Succeeded)
                    {
                        return result2;
                    }
                }
            }
            if (organization.EnableLogin)
            {
                if (organization.Type == OrganizationType.Department)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 不允许启用登录", organization.Name));
                }
            }
            if (organization.Type == OrganizationType.Corporation)
            {
                if (!organization.EnableLogin)
                {
                    return OperationResult.Error(I18N.T("[法人]组织机构 {0} 必须启用登录", organization.Name));
                }
            }
            organization.NormalizedName = NormalizeName(organization.Name);
            //父模块
            if (organization.ParentId == null || Equals(organization.ParentId, default(TOrganizationKey)))
            {
                if (organization.Type != OrganizationType.Virtual && organization.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("顶级组织机构类型必须为[虚拟]或[法人]"));
                }
            }
            string parentTreePathString = null;
            var parent = Organizations.Where(m => Equals(m.Id, organization.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
            if (parent != null)
            {
                parentTreePathString = parent.TreePathString;
            }
            if (parent == null && organization.ParentId != null && !Equals(organization.ParentId, default(TOrganizationKey)))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 的父级 {1} 不存在", organization.Name, organization.ParentId));
            }
            if (organization.EnableLogin && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Department)
                    {
                        return OperationResult.Error(I18N.T("启用登录的组织机构 {0} 存在一个类型为[部门]的父级 {1}", organization.Name, parentOrg.Name));
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
            }
            if (organization.Type == OrganizationType.Department && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Corporation)
                    {
                        break;
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
                parentOrg ??= parent;
                if (parentOrg?.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 的父级 {1} 不为[法人]", organization.Name, parentOrg.Name));
                }
            }

            //重复性检查
            if (Organizations.Any(a => a.Code == organization.Code))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存", organization.Code));
            }
            var exist = Organizations.Where(m => Equals(m.ParentId, organization.ParentId) && Equals(m.Name, organization.Name) && !Equals(m.Id, organization.Id)).Select(n => n.Name).FirstOrDefault();
            if (exist != null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存在名称为 {1} 的子组织机构", exist, organization.Name));
            }

            //排序编号，不存在为1，否则同级最大+1
            if (Equals(organization.OrderNo, default))
            {
                var peerModules = Organizations.Where(m => m.ParentId.Equals(organization.ParentId)).Select(m => new { m.OrderNo }).ToArray();
                if (peerModules.Length == 0)
                {
                    organization.OrderNo = 1;
                }
                else
                {
                    decimal maxCode = peerModules.Max(m => m.OrderNo);
                    organization.OrderNo = maxCode + 1;
                }
            }

            //创建数据
            var result = await OrganizationRepository.InsertAsync(organization);
            if (result.Succeeded)
            {
                organization.TreePathString = organization.ParentId == null ? TreeHelper.FormatTreePathString(organization.Id) : TreeHelper.GetTreePathString(organization.Id, parentTreePathString);
                var result1 = await OrganizationRepository.UpdateAsync(organization);
                if (!result1.Succeeded)
                {
                    return result1;
                }

                //触发创建事件
                EntityEventData<TOrganization> eventData = new(OrganizationRepository.DbContext, OperateType.Insert) { Entities = new List<TOrganization> { organization } };
                await EventBus?.PublishAsync(eventData);

                return OperationResult.Success((object)organization);
            }
            return result;
        }
        #endregion
        #region "异步更新存储中的组织机构"
        /// <summary>
        /// 异步更新存储中的组织机构
        /// </summary>
        /// <param name="organization">要在存储中更新的组织机构</param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns><see cref="Task" /> 表示一个异步的 <see cref="OperationResult" /></returns>
        public virtual async Task<OperationResult> UpdateAsync(TOrganization organization, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNullOrEmpty(organization.Code, nameof(organization.Code));

            var existOrganization = OrganizationRepository.QueryAsNoTracking(o => Equals(o.Id, organization.Id)).FirstOrDefault();
            if (existOrganization == null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不存在", organization.Id));
            }
            if (!Equals(existOrganization.IsSystem, organization.IsSystem))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不能修改 {1} 属性", organization.Id, nameof(organization.IsSystem)));
            }
            if (!Equals(existOrganization.Type, organization.Type))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不能修改 {1} 属性", organization.Id, nameof(organization.Type)));
            }
            if (organization.IsDefault)
            {
                var defaultOrganization = OrganizationRepository.QueryAsNoTracking(m => m.IsDefault && !Equals(m.Id, organization.Id), false).FirstOrDefault();
                if (defaultOrganization != null)
                {
                    defaultOrganization.IsDefault = !organization.IsDefault;
                    var result2 = await OrganizationRepository.UpdateAsync(defaultOrganization);
                    if (!result2.Succeeded)
                    {
                        return result2;
                    }
                }
            }
            if (organization.EnableLogin)
            {
                if (organization.Type == OrganizationType.Department)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 不允许启用登录", organization.Name));
                }
            }
            if (organization.Type == OrganizationType.Corporation)
            {
                if (!organization.EnableLogin)
                {
                    return OperationResult.Error(I18N.T("[法人]组织机构 {0} 必须启用登录", organization.Name));
                }
            }
            organization.NormalizedName = NormalizeName(organization.Name);
            //父模块
            if (organization.ParentId == null || Equals(organization.ParentId, default(TOrganizationKey)))
            {
                if (organization.Type != OrganizationType.Virtual && organization.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("顶级组织机构类型必须为[虚拟]或[法人]"));
                }
            }
            if (Equals(organization.Id, organization.ParentId))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 的父级不能指定为自己", organization.Name));
            }
            string parentTreePathString = null;
            var parent = Organizations.Where(m => Equals(m.Id, organization.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
            if (parent != null)
            {
                parentTreePathString = parent.TreePathString;
            }
            if (organization.EnableLogin && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Department)
                    {
                        return OperationResult.Error(I18N.T("启用登录的组织机构 {0} 存在一个类型为[部门]的父级 {1}", organization.Name, parentOrg.Name));
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
            }
            if (organization.Type == OrganizationType.Department && parent != null)
            {
                var parentOrg = parent;
                while (parentOrg != null)
                {
                    if (parentOrg.Type == OrganizationType.Corporation)
                    {
                        break;
                    }
                    parentOrg = Organizations.Where(m => Equals(m.Id, parentOrg.ParentId)).Select(m => new { m.Id, m.Type, m.Name, m.EnableLogin, m.ParentId, m.TreePathString }).FirstOrDefault();
                }
                if (parentOrg?.Type != OrganizationType.Corporation)
                {
                    return OperationResult.Error(I18N.T("[部门]组织机构 {0} 的父级 {1} 不为[法人]", organization.Name, parentOrg.Name));
                }
            }

            //重复性检查
            if (Organizations.Any(a => a.Code == organization.Code && !Equals(a.Id, organization.Id)))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存", organization.Code));
            }
            var exist = Organizations.Where(m => Equals(m.ParentId, organization.ParentId) && Equals(m.Name, organization.Name) && !Equals(m.Id, organization.Id)).Select(n => n.Name).FirstOrDefault();
            if (exist != null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 中已存在名称为 {1} 的子组织机构", exist, organization.Name));
            }

            //排序编号，不存在为1，否则同级最大+1
            if (Equals(organization.OrderNo, default))
            {
                var peerModules = Organizations.Where(m => m.ParentId.Equals(organization.ParentId)).Select(m => new { m.OrderNo }).ToArray();
                if (peerModules.Length == 0)
                {
                    organization.OrderNo = 1;
                }
                else
                {
                    decimal maxCode = peerModules.Max(m => m.OrderNo);
                    organization.OrderNo = maxCode + 1;
                }
            }

            organization.TreePathString = organization.ParentId == null ? TreeHelper.FormatTreePathString(organization.Id) : TreeHelper.GetTreePathString(organization.Id, parentTreePathString);

            //更新数据
            var result = await OrganizationRepository.UpdateAsync(organization);
            if (result.Succeeded)
            {
                //若父级变更且存在子级，同步更新子级
                if (!Equals(existOrganization.TreePathString, organization.TreePathString))
                {
                    var children = OrganizationRepository.QueryAsNoTracking(o => Equals(o.ParentId, organization.Id)).ToList();
                    if (children?.Count > 0)
                    {
                        foreach (var child in children)
                        {
                            var result2 = await UpdateAsync(child, cancellationToken);
                            if (!result2.Succeeded)
                            {
                                return result2;
                            }
                        }
                    }
                }

                //触发更新事件
                EntityEventData<TOrganization> eventData = new(OrganizationRepository.DbContext, OperateType.Update) { Entities = new List<TOrganization> { organization } };
                await EventBus?.PublishAsync(eventData);

                return OperationResult.Success((object)organization);
            }
            return result;
        }
        #endregion
        #region "异步删除存储中的组织机构"
        /// <summary>
        /// 异步删除存储中的组织机构
        /// </summary>
        /// <param name="organizationId">组织机构编号</param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns><see cref="Task" /> 表示一个异步的 <see cref="OperationResult" /></returns>
        public virtual async Task<OperationResult> DeleteAsync(string organizationId, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNullOrEmpty(organizationId, nameof(organizationId));

            var organization = await OrganizationRepository.GetAsync(ConvertIdFromString(organizationId));
            if (organization == null)
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 不存在", organizationId));
            }
            if (organization.IsSystem)
            {
                return OperationResult.Error(I18N.T("系统组织机构 {0} 不允许删除", organization.Name));
            }
            if (await OrganizationRepository.CheckExistsAsync(m => m.ParentId.Equals(organization.Id)))
            {
                return OperationResult.Error(I18N.T("组织机构 {0} 存在子级", organization.Name));
            }
            //清除附属引用
            await RoleOrganizationRepository.DeleteBatchAsync(m => m.OrganizationId.Equals(organization.Id));
            await UserOrganizationRepository.DeleteBatchAsync(m => m.OrganizationId.Equals(organization.Id));

            var result = await OrganizationRepository.DeleteAsync(organization);
            if (result.Succeeded)
            {
                //触发删除事件
                EntityEventData<TOrganization> eventData = new(OrganizationRepository.DbContext, OperateType.Delete) { Entities = new List<TOrganization> { organization } };
                await EventBus?.PublishAsync(eventData);

                return OperationResult.Success();
            }
            return result;
        }
        #endregion
        #region "异步删除存储中的组织机构"
        /// <summary>
        /// 异步删除存储中的组织机构
        /// </summary>
        /// <param name="organization">组织机构实体</param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns><see cref="Task" /> 表示一个异步的 <see cref="OperationResult" /></returns>
        public virtual async Task<OperationResult> DeleteAsync(TOrganization organization, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));

            return await DeleteAsync(ConvertIdToString(organization.Id), cancellationToken);
        }
        #endregion
        #region "异步查找具有指定ID的组织机构"
        /// <summary>
        /// 异步查找具有指定ID的组织机构
        /// </summary>
        /// <param name="organizationId">要查找的组织机构编号</param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns>包含组织机构的 <see cref="Task" /> 结果</returns>
        public async Task<TOrganization> FindByIdAsync(string organizationId, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();

            var organization = FindById(organizationId);
            return await Task.FromResult(organization);
        }
        #endregion
        #region "异步获取子级组织机构集合"
        /// <summary>
        /// 异步获取子级组织机构集合
        /// </summary>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>子级组织机构集合</returns>
        public virtual async Task<OrganizationDtoSimple[]> GetChildOrganizationsAsync(string organizationId)
        {
            if (organizationId.IsMissing())
            {
                return Array.Empty<OrganizationDtoSimple>();
            }
            List<OrganizationDtoSimple> organizationDtoSimples = new();
            var organization = await OrganizationRepository.GetAsync(ConvertIdFromString(organizationId)) ?? throw new Exception(I18N.T("组织机构 {0} 不存在", organizationId));
            var childOrganizations = OrganizationRepository.QueryAsNoTracking(n => n.TreePathString.Contains(TreeHelper.FormatTreePathString(organizationId)) && !n.Id.Equals(ConvertIdFromString(organizationId))).ToList();
            if (childOrganizations != null)
            {
                foreach (var childOrganization in childOrganizations)
                {
                    organizationDtoSimples.Add(new OrganizationDtoSimple()
                    {
                        Id = ConvertIdToString(childOrganization.Id),
                        Type = childOrganization.Type,
                        Name = childOrganization.Name,
                        Description = childOrganization.Description,

                        OrderNo = childOrganization.OrderNo,
                        TreePathString = childOrganization.TreePathString,
                        ParentId = Equals(childOrganization.ParentId, default) ? null : ConvertIdToString(childOrganization.ParentId.Value),

                        EnableLogin = childOrganization.EnableLogin,
                        IsDefault = childOrganization.IsDefault,
                        IsSystem = childOrganization.IsSystem,

                        IsLocked = childOrganization.IsLocked,

                        CreatedTime = childOrganization.CreatedTime,
                    });
                }
            }
            return organizationDtoSimples.ToArray();
        }
        #endregion
        #region "异步获取父级组织机构集合"
        /// <summary>
        /// 异步获取父级组织机构集合
        /// </summary>
        /// <param name="organizationId">组织机构编号</param>
        /// <returns>父级组织机构集合</returns>
        public virtual async Task<OrganizationDtoSimple[]> GetParentOrganizationsAsync(string organizationId)
        {
            if (organizationId.IsMissing())
            {
                return Array.Empty<OrganizationDtoSimple>();
            }
            List<OrganizationDtoSimple> organizationDtoSimples = new();
            var organization = await OrganizationRepository.GetAsync(ConvertIdFromString(organizationId)) ?? throw new Exception(I18N.T("组织机构 {0} 不存在", organizationId));
            if (!Equals(organization.ParentId, default(TOrganizationKey)))
            {
                var parent = Organizations.Where(m => m.Id.Equals(organization.ParentId)).FirstOrDefault();
                while (parent != null)
                {
                    organizationDtoSimples.Add(new OrganizationDtoSimple()
                    {
                        Id = ConvertIdToString(parent.Id),
                        Type = parent.Type,
                        Name = parent.Name,
                        Description = parent.Description,

                        OrderNo = parent.OrderNo,
                        TreePathString = parent.TreePathString,
                        ParentId = Equals(parent.ParentId, default) ? null : ConvertIdToString(parent.ParentId.Value),

                        EnableLogin = parent.EnableLogin,
                        IsDefault = parent.IsDefault,
                        IsSystem = parent.IsSystem,

                        IsLocked = parent.IsLocked,

                        CreatedTime = parent.CreatedTime,
                    });

                    parent = Organizations.Where(m => m.Id.Equals(parent.ParentId)).FirstOrDefault();
                }
            }
            return organizationDtoSimples.ToArray();
        }
        #endregion

        #region "规范化组织机构名称以进行一致的比较"
        /// <summary>
        /// 规范化组织机构名称以进行一致的比较
        /// </summary>
        /// <param name="organizationName">组织机构名称</param>
        /// <returns>规范化的组织机构名称</returns>
        public virtual string NormalizeName(string organizationName)
        {
            ThrowIfDisposed();
            return organizationName.ToUpper();
        }
        #endregion

        #region "获取树节点及其子节点的所有组织机构编号"
        /// <summary>
        /// 获取树节点及其子节点的所有组织机构编号
        /// </summary>
        /// <param name="rootIds">树节点</param>
        /// <returns>组织机构编号集合</returns>
        public virtual string[] GetTreeIds(params string[] rootIds)
        {
            return rootIds.SelectMany(m => OrganizationRepository.QueryAsNoTracking(n => n.TreePathString.Contains($"${m}$")).Select(n => ConvertIdToString(n.Id))).Distinct().ToArray();
        }
        #endregion

        #region "获取组织机构树形数据"
        /// <summary>
        /// 获取组织机构树形数据
        /// </summary>
        /// <param name="organizationIds">组织机构编号</param>
        /// <returns>组织机构树形数据</returns>
        public virtual OrganizationTreeNode[] GetTreeNodes(params string[] organizationIds)
        {
            List<OrganizationTreeNode> treeNodes = new();
            foreach (var organizationId in organizationIds)
            {
                var organizationEntity = OrganizationRepository.Get(ConvertIdFromString(organizationId));
                if (organizationEntity != null)
                {
                    var treeNode = new OrganizationTreeNode
                    {
                        Id = organizationEntity.Id.ToString(),

                        Type = organizationEntity.Type,
                        Name = organizationEntity.Name,
                        Description = organizationEntity.Description,

                        OrderNo = organizationEntity.OrderNo,
                        TreePathString = organizationEntity.TreePathString,
                        ParentId = organizationEntity.ParentId?.ToString(),

                        EnableLogin = organizationEntity.EnableLogin,
                        IsDefault = organizationEntity.IsDefault,
                        IsSystem = organizationEntity.IsSystem,

                        IsLocked = organizationEntity.IsLocked,

                        CreatedTime = organizationEntity.CreatedTime,
                    };
                    treeNode.Items = GetChild(treeNode);
                    treeNodes.Add(treeNode);
                }
            }
            return treeNodes.ToArray();
        }
        #endregion

        #region "受保护方法 - 获取组织机构子树形节点"
        /// <summary>
        /// 获取组织机构子树形节点
        /// </summary>
        /// <param name="treeNode">树形节点数据</param>
        /// <returns></returns>
        protected virtual List<OrganizationTreeNode> GetChild(OrganizationTreeNode treeNode)
        {
            List<OrganizationTreeNode> child = new();
            var orgChilds = OrganizationRepository.QueryAsNoTracking(m => m.ParentId.Equals(ConvertIdFromString(treeNode.Id))).OrderBy(o => o.OrderNo).ThenBy(m => m.Id).ToList();
            if (orgChilds != null)
            {
                foreach (var orgChild in orgChilds)
                {
                    var childTreeNode = new OrganizationTreeNode
                    {
                        Id = orgChild.Id.ToString(),

                        Type = orgChild.Type,
                        Name = orgChild.Name,
                        Description = orgChild.Description,

                        OrderNo = orgChild.OrderNo,
                        TreePathString = orgChild.TreePathString,
                        ParentId = orgChild.ParentId?.ToString(),

                        EnableLogin = orgChild.EnableLogin,
                        IsDefault = orgChild.IsDefault,
                        IsSystem = orgChild.IsSystem,

                        IsLocked = orgChild.IsLocked,

                        CreatedTime = orgChild.CreatedTime,
                    };
                    if (Organizations.Any(m => m.ParentId.Equals(ConvertIdFromString(childTreeNode.Id))))
                    {
                        childTreeNode.Items = GetChild(childTreeNode);
                    }
                    child.Add(childTreeNode);
                }
            }
            return child;
        }
        #endregion

        #endregion

        #region "方法 - Implementation of IOrganizationClaimStore<TOrganization>"
        #region "获取属于指定 <paramref name="organization"/> 的 <see cref="Claim"/> 的列表"
        /// <summary>
        /// 获取属于指定 <paramref name="organization"/> 的 <see cref="Claim"/> 的列表
        /// </summary>
        /// <param name="organization">要检索的组织机构</param>
        /// <returns>
        /// <see cref="IList{Claim}" /> 结果
        /// </returns>
        public virtual IList<Claim> GetClaims(TOrganization organization)
        {
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));

            IList<Claim> list = OrganizationClaimRepository.QueryAsNoTracking(m => m.OrganizationId.Equals(organization.Id)).Select(n => new Claim(n.ClaimType, n.ClaimValue)).ToList();
            return list;
        }
        #endregion
        #region "向组织机构添加新声明"
        /// <summary>
        /// 向组织机构添加新声明
        /// </summary>
        /// <param name="organization">要向其添加声明的组织机构</param>
        /// <param name="claim">将要添加的 <see cref="Claim" /></param>
        public virtual void AddClaim(TOrganization organization, Claim claim)
        {
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNull(claim, nameof(claim));

            TOrganizationClaim roleClaim = new() { OrganizationId = organization.Id, ClaimType = claim.Type, ClaimValue = claim.Value };
            OrganizationClaimRepository.Insert(roleClaim);
        }
        #endregion
        #region "从组织机构中移除声明"
        /// <summary>
        /// 从组织机构中移除声明
        /// </summary>
        /// <param name="organizationEntity">从中移除声明的组织机构</param>
        /// <param name="claim">将要移除的 <see cref="Claim" /></param>
        public virtual void RemoveClaim(TOrganization organizationEntity, Claim claim)
        {
            ThrowIfDisposed();
            Check.NotNull(organizationEntity, nameof(organizationEntity));
            Check.NotNull(claim, nameof(claim));

            OrganizationClaimRepository.DeleteBatch(m => m.OrganizationId.Equals(organizationEntity.Id) && m.ClaimValue == claim.Type && m.ClaimValue == claim.Value);
        }
        #endregion

        #region "异步获取属于指定 <paramref name="org"/> 的 <see cref="Claim"/> 的列表"
        /// <summary>
        /// 异步获取属于指定 <paramref name="organization"/> 的 <see cref="Claim"/> 的列表
        /// </summary>
        /// <param name="organization">要检索的组织机构</param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns>
        /// 包含 <see cref="IList{Claim}" /> 的 <see cref="Task" /> 结果
        /// </returns>
        public virtual async Task<IList<Claim>> GetClaimsAsync(TOrganization organization, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));

            IList<Claim> list = OrganizationClaimRepository.QueryAsNoTracking(m => m.OrganizationId.Equals(organization.Id)).Select(n => new Claim(n.ClaimType, n.ClaimValue)).ToList();
            return await Task.FromResult(list);
        }
        #endregion
        #region "异步向组织机构添加新声明"
        /// <summary>
        /// 异步向组织机构添加新声明
        /// </summary>
        /// <param name="organization">要向其添加声明的组织机构</param>
        /// <param name="claim">将要添加的 <see cref="Claim" /></param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns>表示异步操作的任务对象</returns>
        public virtual async Task AddClaimAsync(TOrganization organization, Claim claim, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNull(claim, nameof(claim));

            TOrganizationClaim roleClaim = new() { OrganizationId = organization.Id, ClaimType = claim.Type, ClaimValue = claim.Value };
            await OrganizationClaimRepository.InsertAsync(roleClaim);
        }
        #endregion
        #region "异步从组织机构中移除声明"
        /// <summary>
        /// 异步从组织机构中移除声明
        /// </summary>
        /// <param name="organization">从中移除声明的组织机构</param>
        /// <param name="claim">将要移除的 <see cref="Claim" /></param>
        /// <param name="cancellationToken"><see cref="CancellationToken" /> 用于传播应取消操作的通知</param>
        /// <returns>表示异步操作的任务对象</returns>
        public virtual async Task RemoveClaimAsync(TOrganization organization, Claim claim, CancellationToken cancellationToken = new CancellationToken())
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            Check.NotNull(organization, nameof(organization));
            Check.NotNull(claim, nameof(claim));

            await OrganizationClaimRepository.DeleteBatchAsync(m => m.OrganizationId.Equals(organization.Id) && m.ClaimValue == claim.Type && m.ClaimValue == claim.Value);
        }
        #endregion

        #endregion

    }
    #endregion

}
